/* 文档说明： */
/*  主要功能：实现服务端的计算功能     */
#pragma once
#include "Protocol_1.hpp"
enum{
    Div_Zero = 1,
    Mod_Zero,
    Other_Oper
};

// 计算功能：得到序列化的字符串，解析，计算，序列化包装好返回
class ServeCal
{
private:
    Response _Calculate(const Request& req) //实现计算功能的子函数
    {
        Response res(0, 0);
        switch (req._op)
        {
        case '+':
            res._result = req._x + req._y;
            break;
        case '-':
            res._result = req._x - req._y;
            break;
        case '*':
            res._result = req._x * req._y;
            break;
        case '/':
        {
            if (req._y == 0)
                res._exitcode = Div_Zero;
            else
                res._result = req._x / req._y;
        }
        break;
        case '%':
        {
            if (req._y == 0)
                res._exitcode = Mod_Zero;
            else
                res._result = req._x % req._y;
        }
        break;
        default:
            res._exitcode = Other_Oper;
            break;
        }
        return res;
    }
public:
    //实现计算
    std::string Calculate(std::string& req) //不能const引用，req是会被截短的
    {
        //std::cout << "*" << req;
        std::string content; //接受内容
        if(!Depackage(req, &content))
            //return "Calculate fail1..."; //计算失败，格式不合法
            return "";

        Request rqs;
        if(rqs.Deserialize(content) < 0)
            //return "Calculate fail2..."; //反序列化失败
            return "";
        
        Response res = _Calculate(rqs); //得到计算结果

        content = "";
        res.Serialize(&content);
        std::string package;

        Enpackage(content, &package);
        return package;
    }
};